<template>
  <div class="app-container">
    <el-form ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类">
        <!--级联组件-->
        <el-cascader
            :props="categoryProps"
            style="width: 100%"
            v-model="categoryListId"
        />
      </el-form-item>

      <el-form-item label="品牌">
        <el-select
            class="m-2"
            placeholder="选择品牌"
            size="small"
            style="width: 100%"
            v-model="queryParams.brandId"
        >
          <!--
          :key="item.id"   表单迭代元素唯一性
          :label="item.name"  用于显示下拉列选选项名称
          :value="item.id"    提交表单项数据时，提交的品牌id
          -->
          <el-option
              v-for="item in brandList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" id="reset-all">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
        >删除</el-button>
      </el-col>
      <!-- 功能按钮栏 -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据展示表格 -->
    <el-table v-loading="loading" :data="categoryBrandList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="分类名称" prop="categoryName" />
      <el-table-column label="品牌名称" prop="brandName" />
      <el-table-column prop="logo" label="品牌图标" #default="scope">
        <img :src="scope.row.logo" width="50" />
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条组件 -->
    <pagination
        v-show="pagetotal>0"
        :total="pagetotal"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />


    <!-- 添加或修改分类品牌对话框 -->
    <el-dialog :title="title" v-model="open"  width="500px" append-to-body>
      <el-form ref="categoryBrandRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分类" prop="categoryIdList">
          <el-cascader
              :props="categoryProps"
              v-model="form.categoryIdList"
          />
        </el-form-item>
        <el-form-item label="品牌" prop="brandId">
          <el-select
              v-model="form.brandId"
              class="m-2"
              placeholder="选择品牌"
              size="small"
          >
            <el-option
                v-for="item in brandList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button>取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="CategoryBrand">
import { listCategoryBrand,addCategoryBrand,getCategoryBrand,updateCategoryBrand,delCategoryBrand } from "@/api/product/categoryBrand";
//import * as categoryBran from "@/api/product/categoryBrand";
import { getBrandAll } from "@/api/product/brand";
import { getTreeSelect } from "@/api/product/category";

const { proxy  } = getCurrentInstance()

// 定义搜索表单数据模型
const brandList = ref([])

/*const props = {
  lazy: true, // lazy=true表示加载
  value: 'id', // 选中节点后，取分类id的值作为节点value属性值。可以用于搜索
  label: 'name', //显示的是分类名称
  leaf: 'leaf2',  //leaf=true表示叶子节点。没有箭头。不能再查询子节点了。
  async lazyLoad(node, resolve) {   // 加载数据的方法

    if(typeof node.value=='undefined'){ //首次来主页面，需要加载数据，测试node.value为undefined
      const {data} = await getTreeSelect(0)
      resolve(data)  // 返回数据
    }else{
      const {data} = await getTreeSelect(node.value)
      data.forEach(item=>{
        //临时追加一个item.leaf属性。
        item.leaf2 = !item.hasChildren
      })
      resolve(data)  // 返回数据
    }

  }
};*/

const props = {
  lazy: true, // lazy=true表示加载
  value: 'id', // 选中节点后，取分类id的值作为节点value属性值。可以用于搜索
  label: 'name', //显示的是分类名称
  leaf: 'leaf',  //leaf=true表示叶子节点。没有箭头。不能再查询子节点了。
  async lazyLoad(node, resolve) {   // 加载数据的方法
    if(typeof node.value=='undefined'){ //首次来主页面，需要加载数据，测试node.value为undefined
      node.value = 0
    }

    const {data} = await getTreeSelect(node.value)
    data.forEach(item=>{
        //临时追加一个item.leaf属性。
        item.leaf = !item.hasChildren
    })

    resolve(data)  // 返回数据
  }
};
const categoryProps = ref(props)

//定义分页列表数据模型
const categoryBrandList = ref([]);
//定义列表总记录数模型
const pagetotal = ref(0);
//加载数据时显示的动效控制模型
const loading = ref(true);
//定义隐藏搜索控制模型
const showSearch = ref(true);


const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    //搜索商品使用到两个参数：
    brandId: null,
    categoryId: null
  },
  form:{
    id: null,
    brandId: null,
    categoryId: null,
    categoryIdList: []
  },
  rules: {
    categoryIdList: [
      { required: true, message: "分类不能为空", trigger: "blur" }
    ],
    brandId: [
      { required: true, message: "品牌不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams,form,rules } = toRefs(data);

const categoryListId = ref([])  //   [1,2,3]
const open = ref(false)

const title = ref('')

//定义批量操作id列表模型
const ids = ref([]);
//定义单选控制模型
const single = ref(true)

const multiple = ref(true)

//=======================================================

/** 查询分类品牌列表 */
function getList() {
  loading.value = true;

  listCategoryBrand(queryParams.value).then(response => {
    categoryBrandList.value = response.rows;
    pagetotal.value = response.total;
    loading.value = false;
  });
}

getList()



//===================================
function getBrandAllList() {
  getBrandAll().then(result => {
    brandList.value = result.data
  })
}

//自动调用
getBrandAllList()

//===================================
const handleQuery = async ()=>{
  if(categoryListId.value.length==3){
    queryParams.value.categoryId = categoryListId.value[2]
  }
  //total名称冲突，解构起个别名解决问题
  // const { rows,total:mytotal,code,msg } = await listCategoryBrand(queryParams.value)
  // categoryBrandList.value = rows
  // total.value = mytotal

  //total名称冲突，声明响应变量total换成pagetotal，解决问题
  const { rows,total,code,msg } = await listCategoryBrand(queryParams.value)
  categoryBrandList.value = rows
  pagetotal.value = total

  //通过异步请求then()处理，解决问题。
}





//===================================
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加分类品牌";
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    brandId: null,
    categoryId: null,
    categoryIdList: []
  };
  proxy.resetForm("categoryBrandRef");
}

function submitForm(){

  proxy.$refs['categoryBrandRef'].validate(valid=>{
    debugger
    if(valid){
      //if(form.value.categoryIdList.length==3){  //添加或修改，分类选项必填项，无需要配置。表单校验生效即可。
      //form.value.categoryId = categoryListId.value[2]
      form.value.categoryId = form.value.categoryIdList[2]
      //}

      if(!form.value.id ){ //添加
        addCategoryBrand(form.value).then(result=>{
          proxy.$modal.msgSuccess("添加成功")
          open.value = false
          getList()
        })
      }else{
        updateCategoryBrand(form.value).then(result=>{
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      }
    }else{
      proxy.$modal.msgWarning("表单校验失败")
    }
  })


}

//===================================

// 多选框选中数据
function handleSelectionChange(selection) {
  debugger
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getCategoryBrand(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改分类品牌";
  });
}



//===================================

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除分类品牌编号为"' + _ids + '"的数据项？').then(function() {
    return delCategoryBrand(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}


</script>